<!--
 * @Description: 用于编辑模板
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2021-04-28 15:22:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-01-19 16:37:11
-->
<template>
  <div class="new-template">
    <fks-dialog
      v-if="Visible"
      :visible.sync="Visible"
      :append-to-body="true"
      width="1200px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i :class="iconClass" />
        <span>{{ dialogTitle }}</span>
      </template>

      <div class="template">
        <div
          v-loading="loadAll || loadSelect"
          class="template-information"
        >
          <fks-form
            ref="Form"
            :model="Form"
            label-width="84px"
            :rules="rules"
            :disabled="operateType === 'show'"
          >
            <fks-form-item
              :span="12"
              prop="name"
              :label="LANG.NAME"
            >
              <fks-input
                v-model="Form.name"
                maxlength="50"
                show-word-limit
                :read-only="operateType === 'show'"
              />
            </fks-form-item>
            <fks-form-item
              :span="12"
              prop="description"
              :label="LANG.DESCRIPTION"
            >
              <fks-input
                v-model="Form.description"
                maxlength="50"
                show-word-limit
                :read-only="operateType === 'show'"
              />
            </fks-form-item>

            <!-- 模板可选字段 -->
            <fks-form-item
              :span="12"
              :label="LANG.CAN_SELECT_PARAMS"
            >
              <fks-table
                ref="table"
                :data="restField"
                width="50%"
                style="height: 100%"
                max-height="400px"
              >
                <fks-table-column
                  :label="LANG.FIELD_NAME"
                  prop="fieldName"
                  header-align="center"
                  min-width="195px"
                  align="left"
                />
                <fks-table-column
                  :label="LANG.FIELD_SHOW_NAME_DEFAULT"
                  prop="fieldDescribe"
                  header-align="center"
                  width="160px"
                  align="left"
                />
                <fks-table-column
                  :label="LANG.OPERATION"
                  align="center"
                >
                  <template slot-scope="scope">
                    <fks-button
                      type="text"
                      icon="fks-icon-plus"
                      @click="addItem(scope.row)"
                    />
                  </template>
                </fks-table-column>
              </fks-table>
            </fks-form-item>

            <!-- 已存在字段 -->
            <fks-form-item
              :span="12"
              :label="LANG.TEMPLATE_PARAMS"
            >
              <fks-table
                width="50%"
                style="height: 100%"
                :data="selectField"
                max-height="400px"
              >
                <fks-table-column
                  :label="LANG.FIELD_NAME"
                  prop="fieldName"
                  header-align="center"
                  width="180px"
                  align="left"
                />
                <fks-table-column :label="LANG.FIELD_SHOW_NAME">
                  <template slot-scope="scope">
                    <fks-input
                      v-model="scope.row.alias"
                      maxlength="50"
                      show-word-limit
                      @input="inputHandle(scope.$index)"
                    />
                  </template>
                </fks-table-column>
                <fks-table-column
                  :label="LANG.SHOW_ON_LIST"
                  width="80px"
                >
                  <template slot-scope="scope">
                    <fks-switch
                      v-model="scope.row.isReveal"
                      active-value="1"
                      inactive-value="0"
                      :disabled="canShow(scope.row.fieldName)"
                    />
                  </template>
                </fks-table-column>

                <fks-table-column
                  :label="LANG.OPERATION"
                  align="center"
                >
                  <template slot-scope="scope">
                    <fks-button
                      type="text"
                      icon="fks-icon-delete"
                      :disabled="scope.row.canDel === '0'"
                      @click="deleteItem(scope.row)"
                    />
                  </template>
                </fks-table-column>
              </fks-table>
            </fks-form-item>
          </fks-form>
        </div>
      </div>

      <template slot="footer">
        <section>
          <fks-button
            v-show="operateType != 'show'"
            type="primary"
            icon="fks-icon-check"
            :loading="submitLoading"
            @click="submit"
          >
            {{ LANG.SAVE }}
          </fks-button>
        </section>
      </template>
    </fks-dialog>
  </div>
</template>

<script>
import { defaultField, notDisplay } from '@/modules/Content/defaultData'
import {
  addTemplate,
  updateTemplate,
  addTemplateDetail,
  updateTemplateDetail,
  delTemplateDetail,
  getFields
} from './api'
import { getTemplateDetailById } from '@/modules/Content/api'
import * as types from '@/store/Getter/getterTypes.js'
export default {
  name: 'EditTemplate',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    operateType: {
      type: String,
      default: 'new'
    },
    item: {
      type: Object
    }
  },
  data() {
    return {
      loadAll: true,
      loadSelect: true,
      Visible: false,
      submitLoading: false,
      Form: {}, //展示模板基础信息的表单（名字、备注）
      templateId: String,
      detail_del: [], //删除的字段
      detail_add: [], //新增的字段
      detail_update: [], //要更新的字段
      allField: [], //所有可选字段
      restField: [],
      selectField: []
    }
  },
  computed: {
    dialogTitle() {
      if (this.operateType === 'new') return this.LANG.ADD
      if (this.operateType === 'edit') return this.LANG.EDIT
      return this.LANG.VIEW
    },
    iconClass() {
      if (this.operateType === 'new') return 'fks-icon-plus'
      if (this.operateType === 'edit') return 'fks-icon-edit'
      return 'fks-icon-view'
    },
    rules() {
      return {
        name: [
          {
            required: true,
            message: this.LANG.TEMPLATENAME_TIP,
            trigger: 'blur'
          },
          { max: 50, message: this.LANG.ERROR_MAX_50, trigger: 'blur' }
        ],
        description: [
          { max: 50, message: this.LANG.ERROR_MAX_50, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.resetData()
        this.initData()
      }
    }
  },
  methods: {
    close() {
      this.resetData()
      this.$emit('close')
    },
    canShow(name) {
      if (!this.canShow.answers) {
        this.canShow.answers = {}
      }
      if (this.canShow.answers[name] != undefined)
        return this.canShow.answers[name]
      this.canShow.answers[name] = notDisplay.indexOf(name) > -1
      return notDisplay.indexOf(name) > -1
    },

    /**
     * @description: input可能无法更新渲染，手动写一次
     */
    inputHandle(index) {
      let tmpObj = this.selectField[index]
      this.$set(this.selectField, index, tmpObj)
    },

    /**
     * @description: 勾选新的可选字段
     */
    addItem(row) {
      this.selectField.push(row)
      this.restField = this.restField.filter(function (item) {
        return item != row
      })

      //定时发布两个字段联动处理
      if (row.fieldName === 'AUTOPUBLISHFLAG') {
        let childRow = this.findRow('PUBLISHDATE', this.restField)
        if (childRow.fieldName) this.addItem(childRow)
      }
      if (row.fieldName === 'PUBLISHDATE') {
        let childRow = this.findRow('AUTOPUBLISHFLAG', this.restField)
        if (childRow.fieldName) this.addItem(childRow)
      }
    },

    findRow(name, list) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].fieldName === name) return list[i]
      }
      return {}
    },

    /**
     * @description: 删除已勾选字段
     */
    deleteItem(row) {
      this.selectField = this.selectField.filter(function (item) {
        return item != row
      })
      this.restField.push(row)

      //定时发布两个字段联动处理
      if (row.fieldName === 'AUTOPUBLISHFLAG') {
        let childRow = this.findRow('PUBLISHDATE', this.selectField)
        if (childRow.fieldName) this.deleteItem(childRow)
      }
      if (row.fieldName === 'PUBLISHDATE') {
        let childRow = this.findRow('AUTOPUBLISHFLAG', this.selectField)
        if (childRow.fieldName) this.deleteItem(childRow)
      }
    },

    /**
     * @description: 提交时分3类处理：新增/删除/修改
     */
    submit() {
      this.submitLoading = true
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.submitForm()
        }
        if (!valid) {
          this.submitLoading = false
          this.$message({
            type: 'error',
            message: this.LANG.ERROR_UNDO_WRITE
          })
          return
        }
      })
    },

    submitForm: async function () {
      if (this.operateType === 'new') {
        await this.addTemplate()
      }
      if (this.operateType === 'edit') {
        await this.updateTemplate()
      }

      this.detail_del = []
      this.detail_add = []
      this.detail_update = []

      //获取add和update的字段
      this.selectField.forEach((item) => {
        if (item.id) {
          this.detail_update.push(item)
        } else {
          this.detail_add.push(item)
        }
      })
      //获取被删除的字典
      this.restField.forEach((item) => {
        if (item.id) {
          this.detail_del.push(item.id)
        }
      })

      //分别提交
      if (this.detail_add.length > 0) {
        await this.addTemplateDetail()
      }
      if (this.detail_del.length > 0) {
        await this.delTemplateDetail()
      }
      if (this.detail_update.length > 0) {
        await this.updateTemplateDetail()
      }

      //提示
      this.$message({
        type: 'success',
        message:
          this.operateType === 'new'
            ? this.LANG.ADD_SUCCESS
            : this.LANG.EDIT_SUCCESS
      })
      //回调
      this.submitLoading = false
      this.$emit('submit')
    },

    /**
     * @description: 新建模板基本信息，返回模板ID
     */
    addTemplate() {
      let temp = {
        description: this.Form.description,
        name: this.Form.name
      }
      return addTemplate(temp)
        .then((res) => {
          if (res.status) {
            this.templateId = res.data
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 更新模板基本信息
     */
    updateTemplate() {
      let temp = {
        description: this.Form.description,
        name: this.Form.name,
        id: this.templateId
      }
      return updateTemplate(temp)
    },

    /**
     * @description: 提交后对模板的可变字段的相关处理
     */
    addTemplateDetail() {
      this.detail_add.forEach((item) => {
        item.templateId = this.templateId
      })
      return addTemplateDetail(this.detail_add)
    },
    delTemplateDetail() {
      return delTemplateDetail(this.detail_del)
    },
    updateTemplateDetail() {
      return updateTemplateDetail(this.detail_update)
    },

    /**
     * @description: 获得模板所有的字段，置入detailTable进行展示
     * @param {String} id 模板id
     * @return {type}
     */
    getTemplateDetailListById(id) {
      this.loadSelect = true
      return getTemplateDetailById(id)
        .then((res) => {
          this.loadSelect = false
          if (res.status) {
            this.selectField = res.data
              ? JSON.parse(JSON.stringify(res.data))
              : []
            this.selectField.forEach((item) => {
              for (let i = 0; i < defaultField.length; i++) {
                if (defaultField[i].fieldName === item.fieldName) {
                  item.canDel = defaultField[i].canDel
                }
              }
            })
          }
          this.getFields()
            .then(() => this.updateSelected())
            .catch(() => {})
        })
        .catch(() => {
          this.loadSelect = false
        })
    },

    /**
     * @description: 获取所有可选字段
     */
    getFields() {
      this.loadAll = true
      return getFields()
        .then((res) => {
          this.loadAll = false
          if (res.status) {
            this.allField = res.data ? JSON.parse(JSON.stringify(res.data)) : []
            this.allField.forEach((row) => {
              row.id = null
              row.isReveal = 0
              row.alias = JSON.parse(JSON.stringify(row.fieldDescribe))
            })
          }
        })
        .catch(() => {
          this.loadAll = false
        })
    },

    /**
     * @description: 初始化后左侧去除已选择项
     */
    updateSelected() {
      let arr = this.selectField
      this.restField = this.allField.filter((item) => {
        for (let i = 0; i < arr.length; i++) {
          if (item.fieldName === arr[i].fieldName) return false
        }
        return true
      })
    },

    initData() {
      if (this.operateType === 'new') {
        this.selectField = JSON.parse(JSON.stringify(defaultField))
        this.getFields()
          .then(() => {
            this.restField = JSON.parse(JSON.stringify(this.allField))
          })
          .catch(() => {})
        this.loadSelect = false
      }
      if (this.operateType === 'edit' || this.operateType === 'show') {
        this.Form = {
          name: this.item.title,
          description: this.item.description
        }
        this.templateId = this.item.id
        this.getTemplateDetailListById(this.templateId)
      }
    },

    resetData() {
      this.submitLoading = false
      this.Form = {}
      this.templateId = ''
      this.detail_del = []
      this.detail_add = []
      this.detail_update = []
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
  // padding-right: 8px;
}
// ::v-deep .fks-dialog__footer {
//   padding-bottom: 24px;
//   padding-top: 0px;
//   padding-right: 24px;
// }
</style>